/*
 * @FileName: bsp_pwm.h
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-07-12 16:05:59
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-05 13:42:00
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#ifndef __BSP_PWM_H__
#define __BSP_PWM_H__

#ifdef __cplusplus
extern "C" {
#endif

#include "n32g430.h"
#include "n32g430_tim.h"

/**
 * @description PWM相关宏
 */
#define BSP_TIMER_BASE_FREQ        (128e6)      // 128mhz
#define BSP_PWM_FREQ               (100e3)      // 128Khz
#define BSP_TIMER_CNT_RELOAD       (1280)  // 计数器重加载值 中央对齐模式ARR值减一半
#define BSP_PWM_PERIOD             (float)(1.0e-5f)       // pwm周期
#define BSP_PWM_DEADTIME           (1)         // 死区时间 1/128Mhz * 13

/**
 * @description ADC触发策略相关
 */
#define BSP_PWM_TRIG_TH            (230)    // BSP_PWM_PERIOD * 0.18
#define BSP_PWM_TRIG_NOFST         (102)    // BSP_PWM_PERIOD * 0.08

/**
 * @description: 设置PWM周期
 * @param {uint16_t} period 周期宽度
 * @return 无
 */
__STATIC_INLINE void bsp_pwm_period_set(uint16_t period)
{
    TIM1->AR = period;
}

/**
 * @description: 设置PWM占空比
 * @param {uint16_t} duty 脉冲宽度
 * @return 无
 */
__STATIC_INLINE void bsp_pwm_hb1_duty(uint16_t duty)
{
    TIM1->CCDAT4 = duty;
}

/**
 * @description: 设置PWM占空比
 * @param {uint16_t} duty 脉冲宽度
 * @return 无
 */
__STATIC_INLINE void bsp_pwm_hb2_duty(uint16_t duty)
{
    TIM1->CCDAT3 = duty;
}

/**
 * @description: 设置PWM互补输出的死区
 * @param {uint16_t} deadtime 死区宽度
 * @return 无
 */
__STATIC_INLINE void bsp_pwm_deadtime_set(uint16_t deadtime)
{
    TIM1->BKDT = (TIM1->BKDT & 0xFFFFFF00) | deadtime;
}

/**
 * @description: 
 * @param {uint16_t} trig 触发值
 * @return {*}
 */
__STATIC_INLINE void bsp_pwm_trigger_set(uint16_t trig)
{
    TIM1->CCDAT2 = trig;
}

//============================================================
//函数申明区   外部调用
void bsp_pwm_init(void);
bool bsp_pwm_get_ost(void);
void bsp_pwm_clr_ost(void);
void bsp_pwm_sr_control(uint16_t dir, bool en);
void bsp_pwm_dir_config(uint16_t en);
void bsp_pwm_output_enable(void);
void bsp_pwm_output_disable(void);

#ifdef __cplusplus
}
#endif

#endif 
